<template>
  <div class="flex flex-col">
    <!-- 顶部导航 -->
    <div class="flex items-center gap-2 px-4 py-4 h-14 bg-white">
      <!-- <el-button class="mr-2" text @click="goBack"> </el-button> -->
      <ArrowLeft class="!text-base !w-5 !h-5 cursor-pointer grow-0" @click="goBack" title="Back" />

      <div class="flex items-center gap-3">
        <span class="text-lg font-medium"> {{ systemName }} </span>
        <span class="text-sm text-gray-500">{{ systemId }}</span>
        <el-tag :type="getStatusTagType(systemStatus)" v-if="systemStatus !== ''">{{ getStatusLabel(systemStatus) }}</el-tag>
      </div>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="bg-white" @tab-click="handleTabClick">
      <el-tab-pane label="Overview" name="overview">
        <template #label>
          <div class="flex items-center gap-1">
            <Timer class="text-base" />
            <span class="text-base font-normal">{{ "Overview" }}</span>
          </div>
        </template>
        <overview-tab v-if="activeTab === 'overview'" :system-id="systemId" />
      </el-tab-pane>
      <el-tab-pane label="Energy Statistics" name="energy">
        <template #label>
          <div class="flex items-center gap-1">
            <TrendCharts class="text-base" />
            <span class="text-base font-normal">{{ "Energy Statistics" }}</span>
          </div>
        </template>
        <energy-statistics-tab v-if="activeTab === 'energy'" :system-id="systemId" />
      </el-tab-pane>
      <el-tab-pane label="Alert" name="alert">
        <template #label>
          <div class="flex items-center gap-1">
            <Warning class="text-base" />
            <span class="text-base font-normal">{{ "Alert" }}</span>
          </div>
        </template>
        <alert-tab v-if="activeTab === 'alert'" :system-id="systemId" />
      </el-tab-pane>
      <el-tab-pane label="Report" name="report">
        <template #label>
          <div class="flex items-center gap-1">
            <Document class="text-base" />
            <span class="text-base font-normal">{{ "Report" }}</span>
          </div>
        </template>
        <report-tab v-if="activeTab === 'report'" :system-id="systemId" />
      </el-tab-pane>
      <el-tab-pane label="Device" name="device">
        <template #label>
          <div class="flex items-center gap-1">
            <Monitor class="text-base" />
            <span class="text-base font-normal">{{ "Device" }}</span>
          </div>
        </template>
        <device-tab v-if="activeTab === 'device'" :system-id="systemId" />
      </el-tab-pane>
      <el-tab-pane label="Settings" name="settings">
        <template #label>
          <div class="flex items-center gap-1">
            <Setting class="text-base" />
            <span class="text-base font-normal">{{ "Settings" }}</span>
          </div>
        </template>
        <settings-tab v-if="activeTab === 'settings'" :system-id="systemId" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, provide } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ArrowLeft, Timer, TrendCharts, Warning, Document, Monitor, Setting } from "@element-plus/icons-vue";
import { energyAppApi, systemAppApi } from "@/api/business";

// 导入各个标签页组件
import OverviewTab from "./modules/overview/index.vue";
import EnergyStatisticsTab from "./modules/energy-statistics/index.vue";
import AlertTab from "./modules/alert/index.vue";
import ReportTab from "./modules/report/index.vue";
import DeviceTab from "./modules/device/index.vue";
import SettingsTab from "./modules/settings/index.vue";
// import { useI18n } from "@/composables/useI18n";

// const { t } = useI18n();

const route = useRoute();
const router = useRouter();
const activeTab = ref("overview");
const systemId = ref("");
const systemName = ref("");
const systemStatus = ref("");

// 能源数据
const energyData = ref<any>(null);
// const energyLoading = ref(false);

// PV列表数据
const pvListData = ref<any[]>([]);
const pvListLoading = ref(false);

// 安装商系统详情（installer/web/detail）
const installerDetail = ref<any>(null);
const installerDetailLoading = ref(false);
const installerDetailError = ref("");
// 调用能源接口
// const loadEnergyData = async () => {
//   if (!systemId.value || energyLoading.value) return;
//   const pad = (n: number) => String(n).padStart(2, '0');
//   const fmt = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
//   const now = new Date();
//   const start = new Date(now); start.setHours(0, 0, 0, 0);

//   energyLoading.value = true;
//   try {
//     const params = {
//       hemsId: Number(systemId.value),
//       deviceId: 0,
//       // beginDate: fmt(start),
//       // endDate: fmt(now),
//       // startDate: fmt(start),
//       // endStrDate: fmt(now),
//       beginDate: "2025-09-03",
//       endDate: "2025-09-03",
//       startDate: "2025-09-03",
//       endStrDate: "2025-09-03",
//       type: 0,
//       energyType: 0,
//       format: 0
//     };

//     const response = await energyAppApi.postEnergy(params);

//     if (response?.data) {
//       energyData.value = response.data;
//       console.log('能源数据获取成功:', energyData.value);
//     }
//   } catch (error) {
//     console.error('加载能源数据失败:', error);
//   } finally {
//     energyLoading.value = false;
//   }
// };

// 调用PV列表接口
const loadPvList = async () => {
  if (!systemId.value || pvListLoading.value) return;
  const pad = (n: number) => String(n).padStart(2, "0");
  const fmt = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  const now = new Date();
  const start = new Date(now);
  start.setHours(0, 0, 0, 0);

  pvListLoading.value = true;
  try {
    const params = {
      hemsId: Number(systemId.value),
      deviceId: 0,
      beginDate: fmt(start),
      endDate: fmt(now),
      startDate: fmt(start),
      endStrDate: fmt(now),
      type: 0,
      energyType: 0,
      format: 0
    };

    const response = await energyAppApi.postPvList(params);

    if (response?.data) {
      pvListData.value = response.data;
      console.log("PV列表数据获取成功:", pvListData.value);
    }
  } catch (error) {
    console.error("加载PV列表失败:", error);
  } finally {
    pvListLoading.value = false;
  }
};

// 调用installer/web/detail
const loadInstallerDetail = async () => {
  if (!systemId.value || installerDetailLoading.value) return;
  installerDetailLoading.value = true;
  installerDetailError.value = "";
  try {
    const res = await systemAppApi.getDetail({ hemsId: Number(systemId.value) });
    const raw = res?.data || {};

    // 规范化公司地址：若为JSON字符串/对象，优先取 local
    let normalizedAddress = raw.address || "";
    try {
      if (typeof normalizedAddress === "string" && normalizedAddress.trim().startsWith("{")) {
        const obj = JSON.parse(normalizedAddress);
        if (obj && obj.local) normalizedAddress = obj.local;
      } else if (typeof normalizedAddress === "object" && normalizedAddress !== null) {
        if ((normalizedAddress as any).local) normalizedAddress = (normalizedAddress as any).local;
      }
    } catch (_) {
      // 忽略解析失败，使用原值
    }

    // 并网标准转换
    const gridStandardMap: Record<number, string> = {
      0: "德国",
      1: "法国",
      2: "奥地利",
      3: "瑞士",
      4: "荷兰",
      5: "西班牙",
      6: "比利时",
      7: "希腊",
      8: "丹麦",
      9: "意大利"
    };
    let gridStandardText = raw.gridStandard;
    if (typeof raw.gridStandard === "number" && gridStandardMap.hasOwnProperty(raw.gridStandard)) {
      gridStandardText = gridStandardMap[raw.gridStandard as number];
    }

    installerDetail.value = { ...raw, address: normalizedAddress, gridStandard: gridStandardText };
    console.log("installer/web/detail 获取成功:", installerDetail.value);
  } catch (e: any) {
    installerDetailError.value = e?.message || "加载失败";
    console.error("installer/web/detail 获取失败:", e);
  } finally {
    installerDetailLoading.value = false;
  }
};

onMounted(() => {
  // 只取 hemsId
  systemId.value = String(route.query.hemsId || "");
  systemName.value = (route.query.name || "") as string;
  systemStatus.value = (route.query.status || "") as string;

  console.log("[SYS] route.query:", route.query, "final systemId:", systemId.value);

  if (route.query.tab) {
    activeTab.value = route.query.tab as string;
  }

  // 加载能源数据和PV列表数据与installer详情
  if (systemId.value) {
    // loadEnergyData();
    loadPvList();
    loadInstallerDetail();
  }
});

// 下发 provide，供 settings 等子页直接使用
provide("installerDetail", installerDetail);
provide("installerDetailLoading", installerDetailLoading);
provide("installerDetailError", installerDetailError);

// 处理标签点击事件
const handleTabClick = (_tab: any) => {
  // 更新路由查询参数，不刷新页面
  // router.push({
  //   query: { ...route.query, tab: activeTab.value }
  // });
};

// 返回概览页面
const goBack = () => {
  router.push("/overview");
};

// 状态映射：0-正常，1-待机，2-离线，3-故障
const statusConfig = {
  0: { label: "normal", type: "success" },
  1: { label: "standby", type: "warning" },
  2: { label: "offline", type: "info" },
  3: { label: "faulty", type: "danger" }
} as const;

// 获取状态标签类型
const getStatusTagType = (status: string | number) => {
  const statusNum = Number(status);
  return statusConfig[statusNum as keyof typeof statusConfig]?.type || "primary";
};

// 获取状态标签文字
const getStatusLabel = (status: string | number) => {
  const statusNum = Number(status);
  return statusConfig[statusNum as keyof typeof statusConfig]?.label || status;
};
</script>

<style scoped>
:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__nav) {
  /* padding-left: 10px; */
  /* padding-right: 10px; */
  margin-left: 20px;
}

:deep(.el-tabs__item) {
  flex: 1;
  text-align: center;
}

:deep(.el-tabs__content) {
  background-color: #f5f7fa;
  /* overflow: auto; */
}

.main-content {
  padding: 0 !important;
}
</style>
